package edu.chinasoft.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller("typeHandler")
@RequestMapping("/typeHandler")
public class TypeHandler {
    private Logger logger = LoggerFactory.getLogger(TypeHandler.class);
    @RequestMapping(value = "/method01.do",method = RequestMethod.POST)
    public String method01(Date userdate){
        logger.info("时间的值为："+userdate.toLocaleString());

        return "/result/result01";
    }


    @InitBinder
    protected void initBinder(WebDataBinder binder,String userdate) {

        String result="";

        if(userdate.matches("\\d{4}-\\d{2}-\\d{2}")){
            result="yyyy-MM-dd";
        }else if(userdate.matches("\\d{4}:\\d{2}:\\d{2}")){
            result="yyyy:MM:dd";
        }else if(userdate.matches("\\d{4}/\\d{2}/\\d{2}")){
            result="yyyy/MM/dd";
        }


        SimpleDateFormat dateFormat = new SimpleDateFormat(result);
        dateFormat.setLenient(false);
        //注册了类型转换器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

}
